﻿using System;
using System.Messaging;

namespace Patriq.Msmq.Router.Core
{
    public interface IQueueReader : IDisposable
    {
        bool ReadMessage(MessageQueueTransaction trans, out Message message);
    }

    public class QueueReader : IQueueReader
    {
        private readonly MessageQueue queue;
        private readonly TimeSpan queueTimeout;

        public QueueReader(string queuePath, double queueTimeoutInMilli = 1000)
            : this(new MessageQueue(queuePath, QueueAccessMode.Receive), TimeSpan.FromMilliseconds(queueTimeoutInMilli))
        {
        }

        public QueueReader(MessageQueue queue, TimeSpan queueTimeout)
        {
            this.queue = queue;
            this.queueTimeout = queueTimeout;
            this.queue.MessageReadPropertyFilter.SenderId = true;
            this.queue.MessageReadPropertyFilter.SourceMachine = true;
        }

        public bool ReadMessage(MessageQueueTransaction trans, out Message message)
        {
            message = queue.Receive(queueTimeout, trans);
            if (message != null)
                return true;
            return false;
        }

        public void Dispose()
        {
            queue.Dispose();
        }
    }
}